<?php
/**
 * alltosun.com 微信助手类 weixin_helper.php
 * ============================================================================
 * 版权所有 (C) 2009-2013 北京互动阳光科技有限公司，并保留所有权利。
 * 网站地址: http://www.alltosun.com
 * ----------------------------------------------------------------------------
 * 许可声明：这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
 * ============================================================================
 * $Author: 王德康 (wangdk@alltosun.com) $
 * $Date: 2015-3-18 上午10:55:37 $
 * $Id$
 */

class weixin_helper
{
    /**
     * 更新token
     * @param unknown_type $access_token_key
     * @param unknown_type $access_token_expires_key
     * @return mixed|boolean
     */
    private static function update_access_token($access_token_key, $access_token_expires_key) {

        $weixin_config  = Config::Get('openapi');
        if ($weixin_config) {

            $app_id     = $weixin_config['weixin'][0];
            $app_secret = $weixin_config['weixin'][1];

            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$app_id}&secret={$app_secret}";
            $result = an_curl($url, array(), 1, 1);

            if (isset($result['access_token']) && $result['access_token']) {
                $token_info = _model('setting')->read(array('field' => $access_token_key));

                if (!$token_info) {
                    // token
                    _model('setting')->create(array('field'=>$access_token_key, 'value'=>$result['access_token']));
                    // 过期时间
                    _model('setting')->create(array('field'=>$access_token_expires_key, 'value'=>date('Y-m-d H:i:s', time() + $result['expires_in'])));

                } else {

                    _model('setting')->update($token_info['id'], array('value'=>$result['access_token']));
                    _model('setting')->update(array('field' => $access_token_expires_key), array('value'=> time() + $result['expires_in']));

                }

                return $result['access_token'];
            }
        }

        return false;
    }

    /**
     * 获取授权token
     * 自动刷新token
     */
    public static function get_access_token()
    {
        $access_token_key         = 'weixin_access_token';
        $access_token_expires_key = 'weixin_access_token_expires';

        $token_expires_info = _model('setting')->read(array('field' => $access_token_expires_key));

        // 第一次获取
        if (!$token_expires_info) {
            return $this->update_access_token($access_token_key, $access_token_expires_key);
        }

        // 过期
        if ($token_expires_info['value'] <  time()) {
            return $this->update_access_token($access_token_key, $access_token_expires_key);
        }

        $token_info = _model('setting')->read(array('field' => $access_token_key));
        if (!$token_info) {
            return $this->update_access_token($access_token_key, $access_token_expires_key);
        }

        return $token_info['value'];
    }

    /**
     * 获取当前用户的openid
     * @param unknown_type $user_id
     */
    public static function get_user_openid($user_id)
    {
        $info = _model('connect_weixin')->read(array('user_id'=>$user_id));

        if ($info && isset($info['connect_open_id'])) {
            return $info['connect_open_id'];
        }

        return false;
    }


    /**
     * 付款通知
     * @param unknown_type $order_no  商品名称
     */
    public static function send_notify_info($order_no)
    {

        $order_info = order_helper::get_order_info($order_no);
        if ($order_info) {

            $user_id     = $order_info['user_id'];
            $price       = $order_info['price'];
            $goods_name  = $order_info['goods_title'];
            $code        = $order_info['code'];
            $remark      = '凭电子券可在相关店铺进行消费。';

            $openid       = weixin_helper::get_user_openid($user_id);
            $access_token = weixin_helper::get_access_token();

            $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$access_token;


            $data['touser'] = $openid;
            $data['template_id'] = 'yIO82IWNQJBnyf5P4eZvqoZ1dIrY7z04dVCi4Q2P2r0';

            $data['url'] = AnUrl('order');
            $data['topcolor'] = '#FF0000';

            $data['data']['first']['value'] = '恭喜你购买成功';
            $data['data']['first']['color'] = '#173177';

            $data['data']['orderProductPrice']['value'] = $price.'元';
            $data['data']['orderProductPrice']['color'] = '#173177';

            $data['data']['orderProductName']['value'] = $goods_name;
            $data['data']['orderProductName']['color'] = '#173177';

            $data['data']['orderAddress']['value'] = $code;
            $data['data']['orderAddress']['color'] = '#173177';

            $data['data']['orderName']['value'] = $order_no;
            $data['data']['orderName']['color'] = '#173177';

            $data['data']['remark']['value'] = $remark;
            $data['data']['remark']['color'] = '#173177';


            $result = an_curl($url,json_encode($data));

            echo json_encode($result);
        }
    }

}
?>